<template>
  <div v-clickOutside="inputBlurHandler" class="out-container">
    <el-input
      placeholder="请选择"
      @focus="inputFocusHandler"
      class="input"
      :disabled="disabled"
      :clearable="clearable"
      v-model="searchKey"
    />
    <svg-icon
      class="down-icon"
      style="font-size: 32px; padding-right: 6px"
      :style="{ transform: isVisibleTable ? 'rotate(180deg) translateX(5px)' : '' }"
      icon-class="down"
    />
    <div class="container" v-show="isVisibleTable">
      <template v-if="isCollect">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="搜索列表" name="first">
            <SearchList
              :tableData="tableData"
              :tableFields="computedTableFields"
              @keyEnter="keyEnterHandler"
              @change="changeHandler"
              @loveHandler="loveHandler"
            />
          </el-tab-pane>
          <el-tab-pane label="收藏" name="second">
            <CollectHistory
              :collectHistoryList="collectHistoryList"
              :tableData="tableData"
              :tableFields="computedTableFields"
              @keyEnter="keyEnterHandler"
              @change="changeHandler"
              @cancelLoveHandler="cancelLoveHandler"
            />
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else>
        <SearchList
          :tableData="tableData"
          :tableFields="computedTableFields"
          :isCollect="isCollect"
          @keyEnter="keyEnterHandler"
          @change="changeHandler"
        />
      </template>
    </div>
  </div>
</template>

<script>
import SearchList from './SearchList';
import CollectHistory from './CollectHistory';
import SearchModal from './../SearchModal';
/********************************定义一个方法将mixins中的文件全部导入进来 start********************************/
const mixinsList = [];
function importAll(r) {
  r.keys().forEach((key) => mixinsList.push(r(key).default));
}
importAll(require.context('./mixins', true, /\.js/));
/********************************定义一个方法将mixins中的文件全部导入进来 end********************************/

export default {
  name: 'SearchTable',
  mixins: mixinsList,
  props: {
    isCollect: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    // 根据搜索类型来显示不同的表格
    searchType: {
      type: String,
      default: '',
      required: true,
    },
    trigger: {
      type: String,
      default: () => 'focus',
    },
    placement: {
      type: String,
      default: () => 'top',
    },
  },
  data() {
    return {
      isVisibleTable: false,
      searchKey: '',
      activeName: 'first',
      // 选择行列表
      selectRowList: [],
      // 收藏历史记录
      collectHistoryList: [],
      // 表格数据
      tableData: [
        {
          id: 1,
          date: '2016-05-03',
          name: 'Tom1',
          address: 'No. 189, Grove St, Los Angeles',
          age: 20,
        },
        {
          id: 2,
          date: '2016-05-02',
          name: 'Tom2',
          address: 'No. 189, Grove St, Los Angeles',
          age: 30,
        },
        {
          id: 3,
          date: '2016-05-04',
          name: 'Tom3',
          address: 'No. 189, Grove St, Los Angeles',
          age: 40,
        },
        {
          id: 4,
          date: '2016-05-01',
          name: 'Tom4',
          address: 'No. 189, Grove St, Los Angeles',
          age: 50,
        },
      ],
    };
  },
  computed: {
    // 根据类型来选择表格字段
    computedTableFields() {
      return this[`${this.searchType}TableFields`];
    },
  },
  methods: {
    // 获取焦点时候
    inputFocusHandler() {
      this.isVisibleTable = true;
    },
    inputBlurHandler() {
      this.isVisibleTable = false;
    },
    handleClick(e) {
      this.activeName = e.name;
    },
    // 键盘回车事件
    keyEnterHandler(selectRowList) {
      console.log(selectRowList, '选中的数据');
      this.inputBlurHandler();
      this.selectRowList = selectRowList;
    },
    changeHandler(selectRowList) {
      this.selectRowList = selectRowList;
    },
    // 收藏
    loveHandler(rowItem) {
      this.tableData = this.tableData.map((item) => {
        if (item.id == rowItem.id) {
          return {
            ...item,
            love: !!!item.love,
          };
        } else {
          return item;
        }
      });
      // 处理收藏记录
      const collectHistoryList = this.tableData.filter((item) => item.love);
      this.collectHistoryList = collectHistoryList;
      // TODO 调用后端接口
    },
    // 取消收藏
    cancelLoveHandler(rowItem) {
      const collectHistoryList = this.collectHistoryList.filter((item) => item.id != rowItem.id);
      console.log(collectHistoryList, '取消收藏');
      this.collectHistoryList = collectHistoryList;
      if (collectHistoryList && Array.isArray(collectHistoryList) && collectHistoryList.length) {
        const idList = collectHistoryList.map((item) => item.id);
        this.tableData = this.tableData.map((item) => {
          if (!idList.includes(item.id)) {
            return {
              ...item,
              love: false,
            };
          } else {
            return item;
          }
        });
      } else {
        this.tableData = this.tableData.map((item) => {
          return {
            ...item,
            love: false,
          };
        });
      }
      // TODO 调用后端接口
    },
  },
  watch: {
    searchKey: {
      handler(val) {
        // TODO 处理限流操作
        console.log(val, '监听数据变动重新调用接口');
      },
    },
  },
  directives: {
    clickOutside: {
      bind(el, dirs, vNode) {
        const handler = (e) => {
          console.log(el.contains(e.target), '????', el, '----', e.target);
          if (!el.contains(e.target)) {
            vNode.context[dirs.expression](e);
          }
        };
        el.handler = handler;
        document.addEventListener('click', handler);
      },
      unbind(el) {
        document.removeEventListener('click', el.handler);
      },
    },
  },
  watch: {
    isVisibleTable: {
      handler(val) {
        if (!val) {
          this.searchKey = this.selectRowList.map((item) => item.name).join(',');
        }
      },
    },
  },
  components: {
    SearchList,
    CollectHistory,
    SearchModal,
  },
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
